package com.lagou.handler;

import com.lagou.service.RpcRequest;
import com.lagou.service.UserServiceImpl;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;

import java.lang.reflect.Method;

/**
 * 自定义的业务处理器
 */
public class UserServiceHandler extends ChannelInboundHandlerAdapter {

    private ApplicationContext applicationContext;

    public UserServiceHandler(ApplicationContext applicationContext) {
        this.applicationContext = applicationContext;
    }

    /**
     * 当客户端读取数据时，该方法被调用
     * @param ctx
     * @param msg
     * @throws Exception
     */
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        RpcRequest rpcRequest = (RpcRequest)msg;
        //注意：客户端将来发送请求的时候会传递第一个参数:UserService#sayHello#are you ok
        //1.判断当前的请求是否符合规则
        /*UserServiceImpl bean = (UserServiceImpl) applicationContext.getBean(rpcRequest.getClassName());
        if(bean != null){
            String result = bean.sayHello(msg.toString());
            //3.把调用实现类的方法获得的结果写到客户端
            System.out.println(result);
            ctx.writeAndFlush(result);
        }*/
        Object bean = applicationContext.getBean(rpcRequest.getClassName());
        Method method = bean.getClass().getMethod(rpcRequest.getMethodName(), rpcRequest.getParameterTypes());
        Object result = method.invoke(bean, rpcRequest.getParameters());
        ctx.writeAndFlush(result);
    }
}
